package models

import (
	"fmt"
	"xorm.io/builder"
)

type ClosurePoint struct {
	Id        int     `json:"id" xorm:"not null pk autoincr comment('自增主键') INT(11)"`
	ClosureId int     `json:"closureId" xorm:"not null comment('围栏id外键关联dts_closure中的id') index INT(11)"`
	Latitude  float32 `json:"lat" xorm:"not null comment('纬度x/度，单位精确到小数点后6位') FLOAT(15,13)"`
	Longitude float32 `json:"lng" xorm:"not null comment('经度y/度，单位精确到小数点后6位') FLOAT(16,13)"`
	Order     int     `json:"order" xorm:"not null comment('当前点在围栏中的顺序序数') SMALLINT(5)"`
}

type RespClosure struct {
	ClosureId int
	Latitude  float32
	Longitude float32
	Name      string
}

func (c *ClosurePoint) GetClosurePointListByClosureId(id int) (list []*ClosurePoint, err error) {
	err = engine.Table("dts_closure_point").
		Where("closure_id = ?", id).OrderBy("id").
		Find(&list)
	return list, err
}

func (c *ClosurePoint) GetClosurePointByClosureIds(filter builder.Cond) (list []*RespClosure, err error) {
	if err = engine.Table("dts_closure_point").Alias("dcp").
		Select("dcp.closure_id,dcp.latitude,dcp.longitude,df.name").
		Join("LEFT", []string{"dts_closure", "dc"}, "dc.id=dcp.closure_id").
		Join("LEFT", []string{"dts_field", "df"}, "df.id=dc.field_id").
		And(filter).OrderBy("`closure_id`,`order`").Find(&list); err != nil {
	}
	return list, err
}

type Points struct {
	ClosureId int
	Latitude  float32
	Longitude float32
	Order     int
}

func (c *ClosurePoint) GetClosurePoints(school_id int) (list []*Points, err error) {
	sess := engine.Table("dts_field").Alias("f").
		Select("dcp.latitude,dcp.longitude,dcp.order,dcp.closure_id").Join("LEFT", []string{"dts_closure", "dc"}, "dc.field_id=f.id").
		Join("LEFT", []string{"dts_closure_point", "dcp"}, "dcp.closure_id=dc.id").
		Where("f.school_id=? and f.isused =?", school_id, "1").Asc("dcp.order")
	if err = sess.Find(&list); err != nil {
		fmt.Println(err.Error())
		return list, err
	}
	return list, err
}
